package deployr.cli;

import java.io.*;

import javax.servlet.http.*;

public class ResultWriter {

	private final Result result;

	public ResultWriter(Result result) {
		this.result = result;
	}

	public void writeTo(HttpServletResponse response) {
		setStatus(response);
		setContentType(response);
		writeResultTo(response);
	}

	private void writeResultTo(HttpServletResponse response) {
		try {
			PrintWriter output = response.getWriter();
			result.writeTo(output);
			output.flush();
			output.close();
			response.setContentLength(result.getSize());
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	private void setContentType(HttpServletResponse response) {
		response.setContentType(result.getContentType());
	}

	private void setStatus(HttpServletResponse response) {
		response.setStatus(result.getStatus());
	}

}
